<?php

class Mysql {
	//对象的初始化属性
	private $host;
	private $port;
	private $user;
	private $pass;
	private $charset;
	private $dbname;
	private $link;
	private $last_sql;
	/**
	 *初始化类
	 */
	public function __construct($params=array()) {
		$this->host = isset($params['host']) ? $params['host'] : '127.0.0.1';
		$this->port = isset($params['port']) ? $params['port'] : '3306';
		$this->user = isset($params['user']) ? $params['user'] : 'root';
		$this->pass = isset($params['pass']) ? $params['pass'] : '';
		$this->charset = isset($params['charset']) ? $params['charset'] : 'utf8';
		$this->dbname = isset($params['dbname']) ? $params['dbname'] : 'company';
		$this->connect();
		$this->setCharset();
		$this->selectDB();
	}
	/**
	 * 连接数据库
	 */
	private function connect() {
		if(!$link = mysql_connect("$this->host:$this->port", $this->user, $this->pass)) {
			echo '连接失败，请检查mysql服务器，与用户信息';
			die;
		} else {
			$this->link = $link;
		}
	}
	/**
	 * 设置字符集
	 */
	private function setCharset() {
		$sql = "set names $this->charset";
		return $this->query($sql);
	}
	/**
	 * 设置默认数据库
	 */
	private function selectDB() {
		if($this->dbname === '') {
			return ;
		}
		$sql = "use `$this->dbname`";
		return $this->query($sql);
	}
	/**
	 * 执行SQL的方法
	 */
	public function query($sql) {
		$this->last_sql = $sql;
		if(!$result = mysql_query($sql, $this->link)) {
			echo 'SQL执行失败<br>';
			echo '出错了SQL是：', $sql, '<br>';
			echo '错误代码是：', mysql_errno($this->link), '<br>';
			echo '错误信息是：', mysql_error($this->link), '<br>';
			die;
		} else {
			return $result;
		}
	}
	/**
	 * 执行查找SQL并返回符合条件的第一条记录的第一个字段的值
	 */
	public function fetchColumn($sql) {
		if($result = $this->query($sql)) {
			if ($row = mysql_fetch_row($result)) {
				mysql_free_result($result);
				return $row[0];
			} else {
				return false;
			}
		} else {
			return false;
		}
	}
	/**
	 *执行查找SQL并返回二维数组
	 */
	public function fetchAll($sql) {
		if ($result = $this->query($sql)) {
			$rows = array();
			while($row = mysql_fetch_assoc($result)) { $rows[] = $row; }
			mysql_free_result($result);
			return $rows;	
		} else {
			return false;
		}
	}
	/**
	 * 执行SQL获得符合条件的第一条记录
	 */
	public function fetchRow($sql) {
		if ($result = $this->query($sql)) {
			$row = mysql_fetch_assoc($result);
			mysql_free_result($result);
			return $row;
		} else {
			return false;
		}
	}
}